'use strict';
// 小程序UI逻辑代码，此处无法调用酷家乐提供的接口！


function resize() {
    window.parent.postMessage({ type: 'resize' }, '*')
}

function fullscreen() {
    window.parent.postMessage({ type: 'fullscreen' }, '*')
}
function modal() {
    window.parent.postMessage({ type: 'modal' }, '*')
}

function position() {
    window.parent.postMessage({ type: 'position' }, '*')
}

function getUserName() {
    window.parent.postMessage({ type: 'getUserName' }, '*')
}

function send() {
    const input = document.getElementById('thing');
    window.parent.postMessage({ type: 'send', input: input.value }, '*'); // 发送消息至小程序VM代码
}

function getDesignJson(){
    window.parent.postMessage({ type: 'getDesignJson' }, '*')
}

window.addEventListener('message', event => {
    if (event.data.action == 'getUserName') {
        document.getElementById('result1').innerText = event.data.value;
    }
    if (event.data.action == 'send') {
        document.getElementById('result2').innerText = event.data.value;
    }
    if (event.data.action == 'vmLog') {
        console.log('[vmLog]', event.data.value)
    }
    if (event.data.action == 'returnJsonUrl') {
        let JsonUrls = event.data.value; // 假设传入的是一个URL数组
        let results = []; // 存储每个URL返回的result
        let completedCount = 0; // 已完成请求数
        JsonUrls.forEach((JsonUrl, index) => {
            const request = new XMLHttpRequest();
            request.open('GET', JsonUrl);
            request.responseType = 'json';
            request.onload = () => {
                let modelArray = request.response.paramModel;
                console.log(`modelArray from ${JsonUrl}:`, modelArray);
                let result = calculateResult(modelArray);
                console.log(`calculateResult from ${JsonUrl}:`, result);
                results[index] = result;

                completedCount++;
                if (completedCount === JsonUrls.length) {
                    // 所有请求完成，汇总所有结果
                    let totalResult = aggregateResults(results);
                    window.postMessage({action: 'receiveResult', value: totalResult}, '*');
                }
            };
            request.send();
        });
    }
})
function aggregateResults(resultsArray) {
    let allDetails = [];
    let totalProjectionQty = 0;
    let totalExtendQty = 0;

    resultsArray.forEach(result => {
        allDetails = allDetails.concat(result.details);
        totalProjectionQty += result.totals.totalProjectionQty;
        totalExtendQty += result.totals.totalExtendQty;
    });

    return {
        details: allDetails,
        totals: {
            totalProjectionQty,
            totalExtendQty
        }
    };
}

function calculateResult(modelArray) {
    // console.log(modelArray)
    let res= modelArray.map(item => {
        const {x,y,z} = item.boxSize
        const modelName=item.modelName
        const projectionQty=x*z/1000000
        const extendQty=x/1000
        return {modelName,projectionQty,extendQty}
    })
        const totalProjectionQty = res.reduce((sum, item) => sum + item.projectionQty, 0);
        const totalExtendQty = res.reduce((sum, item) => sum + item.extendQty, 0);
    return {
        details: res,
        totals: {
            totalProjectionQty,
            totalExtendQty
        }
    }
}
